package com.qq.connect.oauth;

import com.qq.connect.QQConnect;
import com.qq.connect.QQConnectException;
import com.qq.connect.javabeans.AccessToken;
import com.qq.connect.utils.QQConnectConfig;
import com.qq.connect.utils.RandomStatusGenerator;
import com.qq.connect.utils.http.PostParameter;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Oauth
        extends QQConnect {
    private static final long serialVersionUID = -7860508274941797293L;

    public Oauth(ServletRequest request){
        super(request);
    }

    private String[] extractionAuthCodeFromUrl(String url)
            throws QQConnectException {
        if (url == null) {
            throw new QQConnectException("you pass a null String object");
        }
        Matcher m = Pattern.compile("code=(\\w+)&state=(\\w+)&?").matcher(url);
        String authCode = "";
        String state = "";
        if (m.find()) {
            authCode = m.group(1);
            state = m.group(2);
        }
        return new String[]{authCode, state};
    }

    public AccessToken getAccessTokenByRequest(ServletRequest request)
            throws QQConnectException {
        String queryString = ((HttpServletRequest) request).getQueryString();
        if (queryString == null) {
            return new AccessToken();
        }
        String state = (String) ((HttpServletRequest) request).getSession().getAttribute("qq_connect_state");
        if ((state == null) || (state.equals(""))) {
            return new AccessToken();
        }
        String[] authCodeAndState = extractionAuthCodeFromUrl(queryString);
        String returnState = authCodeAndState[1];
        String returnAuthCode = authCodeAndState[0];

        AccessToken accessTokenObj = null;
        if ((returnState.equals("")) || (returnAuthCode.equals(""))) {
            accessTokenObj = new AccessToken();
        } else if (!state.equals(returnState)) {
            accessTokenObj = new AccessToken();
        } else {
            accessTokenObj = new AccessToken(this.client.post(QQConnectConfig.getValue("accessTokenURL"), new PostParameter[]{new PostParameter("client_id", QQConnectConfig.getValue(keyPre+"app_ID")), new PostParameter("client_secret", QQConnectConfig.getValue(keyPre+"app_KEY")), new PostParameter("grant_type", "authorization_code"), new PostParameter("code", returnAuthCode), new PostParameter("redirect_uri", QQConnectConfig.getValue(keyPre+"redirect_URI"))}, Boolean.valueOf(false)));
        }
        return accessTokenObj;
    }



    /**
     * 获取认证链接
     * 此处加入根据request 域名读取配置
     * 以满足单个应用多个域名认证的需求
     * */
    public String getAuthorizeURL(ServletRequest request)
            throws QQConnectException {
        String state = RandomStatusGenerator.getUniqueState();
        ((HttpServletRequest) request).getSession().setAttribute("qq_connect_state", state);
        String scope = QQConnectConfig.getValue("scope");
        StringBuffer result = new StringBuffer(QQConnectConfig.getValue("authorizeURL").trim())
                .append("?client_id=").append(QQConnectConfig.getValue(keyPre+"app_ID").trim())
                .append("&redirect_uri=").append(QQConnectConfig.getValue(keyPre+"redirect_URI").trim())
                .append("&response_type=code&state=").append(state);
        if ((scope != null) && (!scope.equals(""))) {
            result.append("&scope=").append(scope);
        }
        return result.toString();
    }

}